﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Picture
{
    //https://ai.youdao.com/
    class YouDao_PictureHandleOCR : PictureHandle
    {
        string base64img;
        string salt;
        string curtime;
        SetUpSave _setUpSave;

        public YouDao_PictureHandleOCR()
        {
            _setUpSave = SetUpSave.Create();
        }

        public override string IdentifyImage(Image img)
        {
            var client = new RestClient("https://openapi.youdao.com/ocrapi");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("accept", "application/json");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");

            // base64 string file picture,too long in the case we will omit string
            var bmp = GrayscaleImage(img);
            base64img = ImageToBase64(bmp);

            request.AddParameter("img", base64img);
            string lang = InterfaceAndLanguage.dic["有道"][Program._config._Language];
            request.AddParameter("langType", lang);
            request.AddParameter("detectType", "10012");
            request.AddParameter("imageType", "1");
            request.AddParameter("appKey", _setUpSave.YouDao_App_Key);

            salt = DateTime.Now.Millisecond.ToString();
            request.AddParameter("salt", salt);

            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
            long millis = (long)ts.TotalMilliseconds;
            curtime = Convert.ToString(millis / 1000);
            request.AddParameter("curtime", curtime);

            request.AddParameter("sign", getSign());
            request.AddParameter("docType", "json");
            request.AddParameter("signType", "v3");


            request.AddParameter("ImageBase64", base64img);
            IRestResponse response = client.Execute(request);

            //解析获取的json
            var lst = new List<string>();
            var content = response.Content;
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.Result.regions)
            {
                foreach (var line in item.lines)
                {
                    var a = line.text;
                    lst.Add(line.text.ToString());
                }
            }
            return string.Join("\r\n", lst);
        }

        /// <summary>
        /// 将图片转换为base64
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private string ImageToBase64(Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            string image = Convert.ToBase64String(arr);
            return image;
        }

        protected string Truncate(string baseImg)
        {
            if (baseImg == null)
            {
                return null;
            }
            int len = baseImg.Length;
            return len <= 20 ? baseImg : (baseImg.Substring(0, 10) + len + baseImg.Substring(len - 10, 10));
        }

        protected override string getSign()
        {
            string sign = string.Format("{0}{1}{2}{3}{4}", _setUpSave.YouDao_App_Key, Truncate(base64img), salt, curtime, _setUpSave.YouDao_App_Secret);
            HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
            Byte[] inputBytes = Encoding.UTF8.GetBytes(sign);
            Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
            return BitConverter.ToString(hashedBytes).Replace("-", "");
        }
    }
}
